var dxf2svg = angular.module('dxf2svg', ['ngSanitize', 'ui.select']);

dxf2svg.controller('SVGConverterController', ['$scope', function($scope) {

    /*
     *Retrives Instance Name for the save file function
     */
    instanceName();

    var gUrl = new GlideURL();
    gUrl.setFromCurrent();

    var dataUri = null;
    var layerSelection = [];
    var selectedPathsSvg = "";
    var svgString = null;

    var bounds = [
        [0, 0],
        [600, 800]
    ];

    /*
     *Leaflet Map
     */
    $scope.map = L.map('map', {
        crs: L.CRS.Simple,
        minZoom: 0
    });

    var background = L.imageOverlay("", bounds).addTo($scope.map);
    $scope.map.fitBounds(bounds);

    $scope.convertedFileLayers = [];

    $scope.data = {
        fileData: '',
        layerList: null,
        selectedLayersList: [],
        tempFile: {}
    };


    /*
     * Retrives the Instance Name
     * Uses script include FMFindInstanceName
     */
    function instanceName() {
        var findInstanceNameAjax = new GlideAjax('FMFindInstanceName');
        findInstanceNameAjax.addParam('sysparm_name', 'findInstanceName');
        findInstanceNameAjax.getXML(theParseAnswer);

        function theParseAnswer(response) {
            var answer = response.responseXML.documentElement.getAttribute("answer");
            $scope.instanceName = answer;
        }
    }


    /*
     *
     *Gets the script include FMCreateAttachment parameters
     *add's the parameters from the selected fields to correspondent floor
     *
     */
    $scope.saveFile = function() {
        instanceName();

        overlayOn('overlayS');
        $scope.tableName = gUrl.getParam("sysparm_tableName");
        $scope.recId = gUrl.getParam("sysparm_sys_id");

        var finalSvg = selectedPathsToSvg($scope.data.selectedLayersList);

        var ga = new GlideAjax('x_lsmcb_fm.FMCreateAttachment'); //This argument should be the exact name of the script include.
        ga.addParam('sysparm_name', 'saveAttachment'); //sysparm_name is the name of the function in the script include to call.
        ga.addParam('sysparm_recordId', $scope.recId + '');
        ga.addParam('sysparm_tableName', $scope.tableName + '');
        ga.addParam('sysparm_content', finalSvg + '');
        ga.addParam('sysparm_contentType', 'image/svg+xml');
        ga.addParam('sysparm_fileName', 'image');
        ga.addParam('sysparm_isImage', 'true');

        ga.getXML(myCallBackSave); //This is our callback function, which will process the response.


        function myCallBackSave(response) {
            var answer = response.responseXML.documentElement.getAttribute("answer");
            overlayOff('overlayC');
            //When the file is saved it returns to the correspondent floor
            window.location.href = 'https://' + $scope.instanceName + '.service-now.com/nav_to.do?uri=x_lsmcb_fm_floor.do?sys_id=' + $scope.recId;
        }

    };


    /*
     *
     *Select Layers from imported file and show it on the map leaflet
     *The converted layer are retrieved from the dxf files script converter
     *The selected file layers are divided and show to the map - leaflet -
     */
    try {
        $scope.addSelectLayers = function() {
            for (var i = 0; i < $scope.data.selectedLayersList.length; i++) {
                if ($scope.data.selectedLayersList[i].name == $scope.data.tempFile.name) {
                    $scope.data.tempFile = null;
                    return;
                }
            }

            if ($scope.data.tempFile.name == 'All layers') {
                $scope.data.selectedLayersList = [];
                for (var f = 1; f < $scope.convertedFileLayers.length; f++) {
                    $scope.data.selectedLayersList.push($scope.convertedFileLayers[f]);
                }

                $scope.data.tempFile = null;
            } else {
                $scope.data.selectedLayersList.push($scope.data.tempFile);
                $scope.data.tempFile = null;
            }

            selectedPathsSvg = selectedPathsToSvg($scope.data.selectedLayersList);
            dataUri = 'data:image/svg+xml;utf8,' + encodeURIComponent(selectedPathsSvg);

            $scope.map.removeLayer(background);
            background = L.imageOverlay(dataUri, bounds).addTo($scope.map);
            $scope.map.fitBounds(bounds);

        };


        /*
         *
         *Clear map and $index layers on Choose Layers/UI Page/
         *So whend a new file is imported the map is clear and the layers updated
         *
         */
        $scope.clear = function(event) {
            //Clear $index layer on Choose Layer list and the map
            if ($scope.data.selectedLayersList.splice(event, 1)) {
                selectedPathsSvg = selectedPathsToSvg($scope.data.selectedLayersList);
                dataUri = 'data:image/svg+xml;utf8,' + encodeURIComponent(selectedPathsSvg);

                $scope.map.removeLayer(background);
                background = L.imageOverlay(dataUri, bounds).addTo($scope.map);
                $scope.map.fitBounds(bounds);

            } else {
                //Clear Map and multiple layers on Choose List
                for (var i = 0; i < $scope.data.selectedLayersList.length; i++) {
                    $scope.data.selectedLayersList.splice(event, 1);

                    selectedPathsSvg = selectedPathsToSvg($scope.data.selectedLayersList);
                    dataUri = 'data:image/svg+xml;utf8,' + encodeURIComponent(selectedPathsSvg);

                    $scope.map.removeLayer(background);
                    background = L.imageOverlay(dataUri, bounds).addTo($scope.map);
                    $scope.map.fitBounds(bounds);
                }
            }

        };

    } catch (e) {

    }

    /*
     *
     *Change the choosen Layers List
     *The layer selection that is given to the addSelectedLayer function
     *@param values -Layers from dxf file -
     */
    try {
        $scope.reChange = function(values) {
            layerSelection = [];
            for (var i = 0; i < values.length; i++) {
                layerSelection.push($scope.data.layerList[values[i]]);
            }
            selectedPathsSvg = selectedPathsToSvg(layerSelection);
            dataUri = 'data:image/svg+xml;utf8,' + encodeURIComponent(selectedPathsSvg);

            $scope.map.removeLayer(background);
            background = L.imageOverlay(dataUri, bounds).addTo($scope.map);
            $scope.map.fitBounds(bounds);

        };


    } catch (e) {

    }



    try {
        /*
         *
         *Transforms DXF files in to SVG (Connections to the others UI Scripts for Conversion)
         *The selection of the files and the connection to the other scripts that will convert the files
         *It validates the extensions
         */
        $j(document).ready(function() {
            "use strict";

            var svgString = null;
            var bareFilename = null;
            var fileExtension = null;
            var filename = null;

            /*
             * Imports the DXF file
             */
            $j('#input-file-chooser').change(function() {
                var file = this.files[0];
                filename = file.name;
                var lastDotPosition = filename.lastIndexOf('.');
                bareFilename = filename.substr(0, lastDotPosition);
                fileExtension = filename.substr(lastDotPosition + 1).toLowerCase();
                overlayOn('overlayC');
                /*
                 * Reads the DXF file
                 */
                $j(new FileReader()).load(function(event) {
                    if (event.target.result != null && $scope.data.fileData != event.target.result) {
                        $scope.data.fileData = event.target.result;
                        $scope.reChange(event);
                        $scope.data.selectedLayersList = [];
                        $scope.clear(event);

                        switch (fileExtension) {
                            case 'dxf':
                                $scope.convertedFileLayers = [{ name: 'All layers' }];
                                var convertedFileLayers = dxfToSvg($scope.data.fileData);
                                //filter out empty layers
                                for (var i = 0; i < convertedFileLayers.length; i++) {
                                    if (convertedFileLayers[i].paths != '') {
                                        $scope.convertedFileLayers.push(convertedFileLayers[i]);
                                    }
                                }
                                svgString = selectedPathsToSvg($scope.convertedFileLayers);
                                dataUri = 'data:image/svg+xml;utf8,' + encodeURIComponent(svgString);
                                background = L.imageOverlay(dataUri, bounds).addTo($scope.map);
                                $scope.map.fitBounds(bounds);

                                $scope.data = {
                                    layerList: $scope.convertedFileLayers,
                                    selectedLayersList: []
                                };
                                overlayOff('overlayC');
                                $scope.$apply();
                                break;

                            default:
                                overlayOff('overlayC');
                                background.setUrl('');
                                alert("File extension not valid!!");
                                return;

                        }
                    } else if ($scope.data.fileData == event.target.result) {
                        alert("This file is already in use!");
                    } else {
                        $scope.reChange(event);
                        $scope.data.selectedLayersList = [];
                        $scope.clear(event);
                        $scope.data.fileData = event.target.result;
                    }

                })[0].readAsText(file);
            });

        });
    } catch (e) {

    }
}]);